#!/bin/bash
# Copyright (C) 2024 Chris Caron <lead2gold@gmail.com>
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files(the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions :
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

if [ $(id -u) -eq 0 ]; then
   #
   # Root User
   #
   echo "Apprise API Super User Startup"

   # Default values
   PUID=${PUID:=1000}
   PGID=${PGID:=1000}

   # Lookup our identifier based on the numeric IDs provided.
   GROUP=$(getent group "${PGID}" 2>/dev/null | cut -d: -f1)
   [ -z "${GROUP}" ] && groupadd --force -g "${PGID}" apprise &>/dev/null && \
      GROUP=apprise

   USER=$(id -un "${PUID}" 2>/dev/null)
   if [ $? -ne 0 ]; then
      useradd -M -N -o -u "${PUID}" -G "${GROUP}" \
         -c "Apprise API User" -d /opt/apprise apprise && \
         USER=apprise
   fi

   if [ -z "${USER}" ]; then
      echo "The specified User ID (PUID) of ${PUID} is invalid; Aborting operation."
      exit 1

   elif [ -z "${GROUP}" ]; then
      echo "The specified Group ID (PGID) of ${PGID} is invalid; Aborting operation."
      exit 1
   fi

   # Ensure our group has been correctly assigned
   usermod -a -G "${GROUP}" "${USER}" &>/dev/null || true

   # Allow log redirection even when we later drop privileges.
   chmod o+w /dev/stdout /dev/stderr || true

   # Update our configuration
   sed -i -e "s/^#\?[ \t]*\(user[ \t]*=[ \t]*\).*$/\1${USER}/g" \
      /opt/apprise/webapp/etc/supervisord.conf
   sed -i -e "s/^#\?[ \t]*\(group[ \t]*=[ \t]*\).*$/\1${GROUP}/g" \
      /opt/apprise/webapp/etc/supervisord.conf

else
   #
   # Non-Root User
   #
   echo "Apprise API Non-Super User Startup"
   USER=$(id -un 2>/dev/null || echo apprise)
   GROUP=$(id -gn 2>/dev/null || echo apprise)
fi

# Ensure runtime directories exist; in non-root mode we just best-effort mkdir
[ ! -d /attach ] && mkdir -p /attach 2>/dev/null || true
[ ! -d /config ] && mkdir -p /config 2>/dev/null || true
[ ! -d /config/store ] && mkdir -p /config/store 2>/dev/null || true
[ ! -d /plugin ] && mkdir -p /plugin 2>/dev/null || true
[ ! -d /tmp/apprise ] && mkdir -p /tmp/apprise 2>/dev/null || true

# Permissions
chmod 1777 /tmp/apprise 2>/dev/null || true
chown -R "$USER:$GROUP" /attach /config /config/store \
   /plugin /opt/apprise /tmp/apprise 2>/dev/null || true

if [ ! -z "${HTTP_PORT}" ]; then
  echo -n "Nginx/HTTP over-ride TCP/IP Listen Port: ${HTTP_PORT} ... "
  if [ -w /opt/apprise/webapp/etc/nginx.conf ]; then
    sed -i -e "s/^\([ \t]*listen[ \t]\+[^0-9]*\)\([^;]\+\);\(.*\)/\1${HTTP_PORT};\3/g" \
       /opt/apprise/webapp/etc/nginx.conf &>/dev/null && echo "Done." || echo "Failed!"
  else
    echo "Skipped (nginx.conf not writable)."
  fi
fi

if [ "${IPV4_ONLY+x}" ] && [ "${IPV6_ONLY+x}" ]; then
  echo "ERROR: Both IPV4_ONLY and IPV6_ONLY are set. Exiting."
  exit 1

# Handle IPV4_ONLY flag
elif [ "${IPV4_ONLY+x}" ]; then
  echo -n "Network mode: IPv4-only (IPV4_ONLY set) ... "
  if [ -w /opt/apprise/webapp/etc/nginx.conf ]; then
    sed -ibak -e '/IPv6 Support/d' /opt/apprise/webapp/etc/nginx.conf && \
       echo "Done." || echo "Failed!"
  else
    echo "Skipped (nginx.conf not writable)."
  fi

# Handle IPV6_ONLY flag
elif [ "${IPV6_ONLY+x}" ]; then
  echo -n "Network mode: IPv6-only (IPV6_ONLY set) ... "
  if [ -w /opt/apprise/webapp/etc/nginx.conf ]; then
    sed -ibak -e '/IPv4 Support/d' /opt/apprise/webapp/etc/nginx.conf && \
       echo "Done." || echo "Failed!"
  else
    echo "Skipped (nginx.conf not writable)."
  fi
fi

# The following entry will help identify how internal network configurations
# may be set up on the host that could cause problems.  This is used for debugging
# only; it was originall created to support https://github.com/caronc/apprise-api/issues/262
echo "Resolution of 'localhost' inside container:"
getent ahosts localhost || true

# Get our Port Information
PORT=$(grep -m1 -E '^[ \t]*listen[ \t]+' /opt/apprise/webapp/etc/nginx.conf 2>/dev/null | \
   sed -e 's/^[^0-9]\+\([0-9]\+\).*/\1/g')
PORT=${PORT:=Unknown}

echo "Listening on TCP/IP Port: ${PORT}"
# Working directory
cd /opt/apprise

# Launch our SupervisorD as PID 1
exec /usr/local/bin/supervisord -c /opt/apprise/webapp/etc/supervisord.conf

# Always return our SupervisorD return code
exit $?
